package org.example.managere.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
// @EnableTransactionManagement  // 注释掉这行
@EnableJpaRepositories(
        basePackages = "org.example.managere.repository.operationdata",
        entityManagerFactoryRef = "operationdataEntityManager",
        transactionManagerRef = "operationdataTransactionManager"
)
public class OperationdataDataSourceConfig {
    @Primary
    @Bean(name = "operationdataDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.operationdata")
    public DataSource operationdataDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "operationdataEntityManager")
    public LocalContainerEntityManagerFactoryBean operationdataEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(operationdataDataSource());
        em.setPackagesToScan("org.example.managere.entity.operationdata");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean(name = "operationdataTransactionManager")
    public PlatformTransactionManager operationdataTransactionManager(
            @Qualifier("operationdataEntityManager") LocalContainerEntityManagerFactoryBean operationdataEntityManager) {
        return new JpaTransactionManager(operationdataEntityManager.getObject());
    }
} 